package handler

import (
	"gitee.com/sansaniot/ssiot-core/logger"
	"gitee.com/sansaniot/ssiot-core/msg/sms"
	"gitee.com/sansaniot/ssiot-core/msg/sms/model"
	"gorm.io/gorm"

	"ssnotify/common/enums/recordstatus"
	"ssnotify/common/enums/sendway"
	"ssnotify/common/utils"
	"ssnotify/internal/notify/models"
)

// 短信通知
func SendShortMsgNotify(db *gorm.DB, templateId string, notifyData map[string]interface{}, notifyConfig models.NotifyConfig, notifyUserList []models.NotifyUser) {
	if len(templateId) == 0 {
		return
	}
	//日志
	logger.Info("************发送短信通知开始************")
	//获取当前通知对应的模板配置集合
	notifyTemplateList := getNotifyTemplateList(db, templateId, sendway.ShortMsg.Get().SendType)
	//遍历用户信息(每个用户发送一次获取成功或失败响应)
	for _, userItem := range notifyUserList {
		mobile := userItem.Mobile
		if len(mobile) == 0 {
			continue
		}
		var sendResult models.NotifySendResult
		sendResult.SendStatus = recordstatus.NotSend.Get().Key
		sendResult.SendWay = sendway.ShortMsg.Get().SendType
		for _, notifyTemplate := range notifyTemplateList {
			sendSms(mobile, notifyData, notifyTemplate, &sendResult)
		}
		//初始化缓存通知记录
		addNotifyRecordQueue(notifyData, notifyConfig, userItem, &sendResult)
	}
}

// 发送短信
func sendSms(mobile string, notifyData map[string]interface{}, notifyTemplate models.NotifyTemplate, sendResult *models.NotifySendResult) {
	if len(mobile) == 0 {
		return
	}
	//消息通知模板参数
	sendParam := formatNotifySmsParam(notifyData, notifyTemplate.Content)
	//短信工具类
	if err := sms.SendSMSByData(model.SMSCustParam{
		Phone: []string{mobile},
		Param: sendParam,
		Code:  notifyTemplate.Id,
	}); err != nil {
		sendResult.SendStatus = utils.If(sendResult.SendStatus != recordstatus.NotSend.Get().Key, sendResult.SendStatus, recordstatus.SendFail.Get().Key).(string)
		sendResult.ErrorInfo = utils.If(sendResult.SendStatus != recordstatus.SendFail.Get().Key, sendResult.ErrorInfo, err.Error()).(string)
		logger.Errorf("短信通知发送异常 err=[%+v]", err)
	} else {
		sendResult.SendStatus = recordstatus.SendSuccess.Get().Key
		logger.Infof("短信通知发送成功 mobile=[%+v]", mobile)
	}
	//判断是否指定通知content
	if len(utils.GetStringValueFiled(notifyData, "remark")) == 0 {
		if len(sendResult.SendContent) == 0 {
			sendResult.SendContent = make([]map[string]string, 0)
		}
		sendResult.SendContent = append(sendResult.SendContent, map[string]string{"sms": formatNotifyEmailContent(notifyTemplate.Content, notifyData)})
	}
}

// 格式处理消息通知模板参数
func formatNotifySmsParam(notifyData map[string]interface{}, templateContent string) map[string]string {
	sendParam := make(map[string]string)
	//获取占位符号内容
	templateKeys := utils.GetTemplateKey(templateContent, "{", "}")
	//遍历处理和缓存
	for _, keyVal := range templateKeys {
		//有效存在
		if val, ok := notifyData[keyVal]; ok {
			//缓存所有的模板参数
			sendParam[keyVal] = utils.InterfaceToStr(val)
		} else {
			//不存在 缓存空内容
			sendParam[keyVal] = ""
		}
	}
	//返回
	return sendParam
}
